package chen.yi.common.decryption;

import chen.yi.component.data.desensitization.decryption.DataDecryption;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.springframework.stereotype.Component;

/**
 * @author huat
 **/
@Component
public class DataDecryptionImpl implements DataDecryption {
    private final static String KEY = "chen.yi.vue.key.";
    private final static SymmetricCrypto AES;

    static {
        //随机生成密钥
        byte[] key = KEY.getBytes();

        AES = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

    }

    /**
     * aes对称加密
     *
     * @param data 待加密数据
     * @return 加密后的数据
     */
    @Override
    public Object encrypt(Object data) {
        if (data instanceof String) {
            byte[] encrypt = AES.encrypt(data.toString());
            return AES.encryptHex(encrypt);
        }
        return data;
    }

    /**
     * AES解密数据
     *
     * @param encryptData 加密数据
     * @return 解密后的数据
     */
    @Override
    public Object decrypt(Object encryptData) {
        if (encryptData instanceof String) {
            byte[] decrypt = AES.decrypt(encryptData.toString());
            return AES.decryptStr(decrypt, CharsetUtil.CHARSET_UTF_8);
        }
        return encryptData;
    }
}
